import 'package:flutter/material.dart';
import 'package:flutter_base/pages/order/model/model_order_tags.dart';
import 'package:flutter_base/pages/order/widgets/order_top_dialog.dart';
import 'package:flutter_base/widgets/image/image_view.dart';
import 'package:flutter_base/widgets/keep_alive_widget.dart';
import 'package:flutter_base/widgets/tab/common_tab_bar_page.dart';
import 'package:flutter_base/widgets/tab/custom_tab_bar_view.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:flutter_base/base/widget/base_get_builder.dart';
import 'package:flutter_base/config/app_color.dart';
import 'package:flutter_base/config/app_config.dart';
import 'package:flutter_base/widgets/appbar/common_app_bar.dart';
import 'package:flutter_base/widgets/tab/common_tab_bar.dart';
import 'package:flutter_base/widgets/widget_line.dart';
import 'package:flutter_base/widgets/image/auto_image.dart';
import 'package:flutter_base/widgets/button/common_button.dart';
import 'package:flutter_base/generated/assets.dart';
import 'order_logic.dart';

class OrderPage extends StatelessWidget {
  final logic = Get.put(OrderLogic());

  OrderPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return BaseGetBuilder<OrderLogic>(
      // appBar: CommonAppBar(
      //   title: '我的订单',
      //   showLeft: false,
      //   backgroundColor: Colors.white,
      // ),

      backgroundColor: AppColor.colorF5F7FA,
      builder: (_) {
        return Column(
          children: [
            Container(
                padding: EdgeInsets.only(top: ScreenUtil().statusBarHeight),
                color: Colors.transparent,
                height: ScreenUtil().statusBarHeight + kToolbarHeight,
                child: Row(
                  children: [
                    Expanded(
                      child: CommonTabBar(
                        tabContentPadding: EdgeInsets.zero,
                        tabController: logic.tabController,
                        tabs: logic.orderList
                            .map((e) => Text(e.title ?? ''))
                            .toList(),
                        labelColor: AppColor.color0C0A09,
                        unselectedLabelColor: AppColor.color8D8D99,
                        labelStyle: TextStyle(
                          fontSize: 16.sp,
                          fontWeight: FontWeight.w600,
                        ),
                        unselectedLabelStyle: TextStyle(
                          fontSize: 16.sp,
                          fontWeight: FontWeight.w400,
                        ),
                        onTap: (index) => logic.onTabChanged(index),
                      ),
                    ),
                    12.horizontalSpace,
                    GestureDetector(
                      onTap: () {
                        OrderTopDialog(psychologyTypes: logic.psychologyTypes)
                            .show()
                            .then((value) {
                          if (value is ModelOrderTags) {
                            logic.tabController.animateTo(
                                logic.psychologyTypes.indexOf(value));
                          }
                        });
                      },
                      behavior: HitTestBehavior.opaque,
                      child: SizedBox(
                        width: 40,
                        height: 40,
                        child: Center(
                          child: AutoImage(
                            Assets.commonArrowDown,
                            width: 24.w,
                          ),
                        ),
                      ),
                    )
                  ],
                )),
            Expanded(
              child: CustomTabBarView(
                controller: logic.tabController,
                children: logic.orderList.map((e) {
                  return KeepAliveWidget(
                    child: e.view,
                  );
                }).toList(),
              ),
            ),
          ],
        );
      },
    );
  }

  // 订单列表
  Widget _buildOrderList(List<Map<String, dynamic>> orders) {
    if (orders.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            AutoImage(
              Assets.emptyNoData,
              width: 80.w,
              height: 80.w,
            ),
            SizedBox(height: 16.w),
            Text(
              '暂无订单',
              style: TextStyle(
                fontSize: 16.sp,
                color: AppColor.color8D8D99,
              ),
            ),
          ],
        ),
      );
    }

    return ListView.separated(
      padding: EdgeInsets.all(16.w),
      itemCount: orders.length,
      separatorBuilder: (context, index) => SizedBox(height: 12.w),
      itemBuilder: (context, index) => _buildOrderItem(orders[index]),
    );
  }

  // 订单项
  Widget _buildOrderItem(Map<String, dynamic> order) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12.w),
        boxShadow: [
          BoxShadow(
            color: AppColor.color0C0A09.withOpacity(0.05),
            blurRadius: 8.w,
            offset: Offset(0, 2.w),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 订单头部
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.w),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  '订单号: ${order['orderNo']}',
                  style: TextStyle(
                    fontSize: 14.sp,
                    color: AppColor.color8D8D99,
                  ),
                ),
                Text(
                  _getOrderStatusText(order['status']),
                  style: TextStyle(
                    fontSize: 14.sp,
                    color: _getOrderStatusColor(order['status']),
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ],
            ),
          ),

          WidgetLine(
            height: 1.w,
          ),

          // 订单内容
          Padding(
            padding: EdgeInsets.all(16.w),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 商品图片
                Container(
                  width: 80.w,
                  height: 80.w,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(8.w),
                    color: AppColor.colorF8F9FD,
                  ),
                  child: Center(
                    child: ImageView(
                      imageUrl: "${AppConfig.testImage}",
                      width: 80.w,
                      height: 80.w,
                      fit: BoxFit.cover,
                      // borderRadius: BorderRadius.circular(8.w),
                    ),
                  ),
                ),

                SizedBox(width: 12.w),

                // 商品信息
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        order['productName'],
                        style: TextStyle(
                          fontSize: 16.sp,
                          fontWeight: FontWeight.w600,
                          color: AppColor.color0C0A09,
                        ),
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                      ),
                      SizedBox(height: 4.w),
                      Text(
                        order['specification'],
                        style: TextStyle(
                          fontSize: 14.sp,
                          color: AppColor.color8D8D99,
                        ),
                      ),
                      SizedBox(height: 8.w),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(
                            '¥${order['price']}',
                            style: TextStyle(
                              fontSize: 16.sp,
                              color: AppColor.errorColor,
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                          Text(
                            'x${order['quantity']}',
                            style: TextStyle(
                              fontSize: 14.sp,
                              color: AppColor.color8D8D99,
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),

          WidgetLine(
            height: 1.w,
          ),

          // 订单底部
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.w),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  '共${order['quantity']}件商品 合计:',
                  style: TextStyle(
                    fontSize: 14.sp,
                    color: AppColor.color8D8D99,
                  ),
                ),
                Text(
                  '¥${order['totalAmount']}',
                  style: TextStyle(
                    fontSize: 16.sp,
                    color: AppColor.errorColor,
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ],
            ),
          ),

          // 操作按钮
          if (order['status'] != 4)
            Padding(
              padding: EdgeInsets.fromLTRB(16.w, 0, 16.w, 16.w),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: _buildActionButtons(order),
              ),
            ),
        ],
      ),
    );
  }

  // 根据订单状态构建操作按钮
  List<Widget> _buildActionButtons(Map<String, dynamic> order) {
    List<Widget> buttons = [];

    // 所有状态都有查看详情
    buttons.add(
      _buildButton('查看详情', false, () => _onViewOrderDetail(order)),
    );

    // 根据订单状态添加不同按钮
    switch (order['status']) {
      case 1: // 待付款
        buttons.add(SizedBox(width: 12.w));
        buttons.add(
          _buildButton('去支付', true, () => _onPayOrder(order)),
        );
        break;
      case 2: // 待发货
        buttons.add(SizedBox(width: 12.w));
        buttons.add(
          _buildButton('提醒发货', false, () => _onRemindShipment(order)),
        );
        break;
      case 3: // 待收货
        buttons.add(SizedBox(width: 12.w));
        buttons.add(
          _buildButton('确认收货', true, () => _onConfirmReceipt(order)),
        );
        break;
      default:
        break;
    }

    return buttons;
  }

  // 查看订单详情
  void _onViewOrderDetail(Map<String, dynamic> order) {
    // 这里实现查看详情的逻辑
  }

  // 支付订单
  void _onPayOrder(Map<String, dynamic> order) {
    // 这里实现支付订单的逻辑
  }

  // 提醒发货
  void _onRemindShipment(Map<String, dynamic> order) {
    // 这里实现提醒发货的逻辑
  }

  // 确认收货
  void _onConfirmReceipt(Map<String, dynamic> order) {
    // 这里实现确认收货的逻辑
  }

  // 构建按钮
  Widget _buildButton(String text, bool isPrimary, Function onTap) {
    return InkWell(
      onTap: () => onTap(),
      borderRadius: BorderRadius.circular(20.w),
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.w),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(20.w),
          color: isPrimary ? AppColor.primary : Colors.white,
          border: Border.all(
            color: isPrimary ? AppColor.primary : AppColor.colorCCCCCC,
            width: 1.w,
          ),
        ),
        child: Text(
          text,
          style: TextStyle(
            fontSize: 14.sp,
            color: isPrimary ? Colors.white : AppColor.color8D8D99,
            fontWeight: isPrimary ? FontWeight.w600 : FontWeight.normal,
          ),
        ),
      ),
    );
  }

  // 获取订单状态文本
  String _getOrderStatusText(int status) {
    switch (status) {
      case 1:
        return '待付款';
      case 2:
        return '待发货';
      case 3:
        return '待收货';
      case 4:
        return '已完成';
      case 5:
        return '已取消';
      default:
        return '未知状态';
    }
  }

  // 获取订单状态颜色
  Color _getOrderStatusColor(int status) {
    switch (status) {
      case 1:
        return AppColor.colorFFDD00;
      case 2:
        return AppColor.primary;
      case 3:
        return AppColor.color04B822;
      case 4:
        return AppColor.color8D8D99;
      case 5:
        return AppColor.errorColor;
      default:
        return AppColor.color8D8D99;
    }
  }
}
